package www.webols.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public class HttpsUtils {
	public static final String API_ROOT = "https://api.weibo.com";
	public static final String TOKEN_URI = "/oauth2/access_token";
	public static final String PARAM_CLIENT_ID = "client_id";
	public static final String PARAM_CLIENT_SECRET = "client_secret";
	public static final String PARAM_GRANT_TYPE = "grant_type";
	public static final String PARAM_CODE = "code";
	public static final String PARAM_REDIRECT_URI = "redirect_uri";

	public static final String WEIBO_OAUTH_URL = "https://api.weibo.com/2/oauth2/authorize?client_id=3723310027&display=mobile&redirect_uri=http://dev.19lou.cn&response_type=code";
	public static final String WEIBO_APP_KEY = "3723310027";
	public static final String WEIBO_APP_SECRET = "2a5fce0539beddf093f976ed188d3d58";
	public static final String WEIBO_REDIRECT_URL = "http://dev.19lou.cn";
	
	
	private SSLContext sslContext=null;
	private X509TrustManager xtm = new X509TrustManager() {
		public void checkClientTrusted(X509Certificate[] chain, String authType) {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) {
			System.out.println("cert: " + chain[0].toString() + ", authType: "
					+ authType);
		}

		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	};
	private HostnameVerifier hnv = new HostnameVerifier() {
		public boolean verify(String hostname, SSLSession session) {
			System.out.println("hostname: " + hostname);
			return true;
		}
	};

	public HttpsUtils() {
		
		try {
			sslContext = SSLContext.getInstance("TLS");
			X509TrustManager[] xtmArray = new X509TrustManager[] { xtm };
			sslContext.init(null, xtmArray, new java.security.SecureRandom());
		} catch (GeneralSecurityException gse) {
		}
		if (sslContext != null) {
			HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
					.getSocketFactory());
		}
		//Scheme scheme=new Scheme("https",sslContext.getServerSocketFactory(),443);

		HttpsURLConnection.setDefaultHostnameVerifier(hnv);
	}

	public String run(String urlPath,Map<String,String> params) {		
		
		
		
		StringBuffer json = new StringBuffer();
		URL url = null;
		HttpsURLConnection urlCon = null;
		BufferedReader in = null;
		try {
//			if (Constant._httpType == Constant.HTTP_TYPE_CMWAP) {
//				url = new URL(urlPath);
//				Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,
//						new InetSocketAddress("10.0.0.172", 80));
//				urlCon = (HttpsURLConnection) url.openConnection(proxy);
//			} else {
				url = new URL(urlPath);
				urlCon = (HttpsURLConnection) url.openConnection();
//			}
			urlCon.setReadTimeout(2000);
			urlCon.setConnectTimeout(5000);
			urlCon.setDoInput(true);
			urlCon.setDoOutput(true);
			urlCon.setDoInput(true);
			urlCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			
			urlCon.setRequestProperty("Accept-Encoding", "identity");
			
			
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			Iterator<String> keys = params.keySet().iterator();
			while (keys.hasNext()) {
				String key = keys.next();
				formparams.add(new BasicNameValuePair(key, params.get(key)));
			}
			
				UrlEncodedFormEntity uefEntity;

				uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
				uefEntity.setContentType("application/x-www-form-urlencoded");
				
			//String params="client_id=3723310027&client_secret=2a5fce0539beddf093f976ed188d3d58&grant_type=authorization_code&redirect_uri=http://dev.19lou.cn&code=b1e17f7071c0127313e0b55d78b3fde2client_id=3723310027&client_secret=2a5fce0539beddf093f976ed188d3d58&grant_type=authorization_code&redirect_uri=http://dev.19lou.cn&code=b1e17f7071c0127313e0b55d78b3fde2";
			//urlCon.setRequestProperty("Content-Length", ""+params.length());
		
			
			//urlCon.connect();
			//DataOutputStream wr = new DataOutputStream(urlCon.getOutputStream()); 
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();  
			
			
			uefEntity.writeTo(urlCon.getOutputStream());
			
			
			
			//wr.close(); 
			
			int code=urlCon.getResponseCode();
			
			if(code>=400){
				String msg=urlCon.getResponseMessage();
				Map<String,List<String>> headers= urlCon.getHeaderFields();
				for(String key: headers.keySet())
				{
					List<String> values=headers.get(key);
					
					msg+="\n"+key+" = "+ values.get(0);
				}
				msg+=" \n ContentType="+urlCon.getContentType();
				msg+=" \n Content=" +urlCon.getContentLength();
				
				Log.d("Error Code: ",""+code );
				Log.d("Msg:",msg);
				
				java.io.InputStream inn=urlCon.getErrorStream();
				
				in = new BufferedReader(new InputStreamReader(inn));
				StringBuffer errMsg=new StringBuffer();
				String line;
				while ((line = in.readLine()) != null) {
					errMsg.append(line);
				}
				Log.d("Error Message:",errMsg.toString());
			}
			else if(code==200){
				Log.d("get token result:","success");
				in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
				String line;
				while ((line = in.readLine()) != null) {
					json.append(line);
				}
			}
			
		} catch (MalformedURLException mue) {
			mue.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
					in = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != urlCon) {
				urlCon.disconnect();
				urlCon = null;
			}
		}
		return json.toString();
	}
}